<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>基于zookeeper实现分布式锁 | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第二十七篇博客–基于zookeeper实现分布式锁 分布式锁设计zookeeper的临时节点在会话断开后，则会自动删除，这个特性使其可以非常好的应用在分布式锁而如果直接使用某一个path的临时节点作为分布式锁，会导致”惊群效应“（当锁每次释放都会唤醒全部竞争节点，而实际只能有一个竞争到）所以结合有序节点进行优化，对于某一个特定的节点RootNode创建临时有序子节点当一个客户端">
<meta property="og:type" content="article">
<meta property="og:title" content="基于zookeeper实现分布式锁">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/08/01/基于zookeeper实现分布式锁/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第二十七篇博客–基于zookeeper实现分布式锁 分布式锁设计zookeeper的临时节点在会话断开后，则会自动删除，这个特性使其可以非常好的应用在分布式锁而如果直接使用某一个path的临时节点作为分布式锁，会导致”惊群效应“（当锁每次释放都会唤醒全部竞争节点，而实际只能有一个竞争到）所以结合有序节点进行优化，对于某一个特定的节点RootNode创建临时有序子节点当一个客户端">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-08-01T08:27:30.222Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="基于zookeeper实现分布式锁">
<meta name="twitter:description" content="欢迎查看Eetal的第二十七篇博客–基于zookeeper实现分布式锁 分布式锁设计zookeeper的临时节点在会话断开后，则会自动删除，这个特性使其可以非常好的应用在分布式锁而如果直接使用某一个path的临时节点作为分布式锁，会导致”惊群效应“（当锁每次释放都会唤醒全部竞争节点，而实际只能有一个竞争到）所以结合有序节点进行优化，对于某一个特定的节点RootNode创建临时有序子节点当一个客户端">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-基于zookeeper实现分布式锁" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/08/01/基于zookeeper实现分布式锁/" class="article-date">
  	<time datetime="2019-08-01T08:01:55.356Z" itemprop="datePublished">2019-08-01</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      基于zookeeper实现分布式锁
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第二十七篇博客–基于zookeeper实现分布式锁</p>
<h2 id="分布式锁设计"><a href="#分布式锁设计" class="headerlink" title="分布式锁设计"></a>分布式锁设计</h2><p>zookeeper的临时节点在会话断开后，则会自动删除，这个特性使其可以非常好的应用在分布式锁<br>而如果直接使用某一个path的临时节点作为分布式锁，会导致”惊群效应“（当锁每次释放都会唤醒全部竞争节点，而实际只能有一个竞争到）<br>所以结合有序节点进行优化，对于某一个特定的节点RootNode创建临时有序子节点<br>当一个客户端要获取锁时，就会新增一个临时有序子节点<br>在尝试获取锁时进行判断，查看RootNode当前的所有子节点信息，判断自己是否是最小的子节点（因为zookeeper的有序节点会从1递增）<br>如果是最小的子节点，则获得锁，在释放锁时，删除自己创建的这个临时有序节点<br>如果不是最小节点，代表还有别人在占用锁，则注册一个事件监听子节点中节点序号刚好小于自己的节点的删除事件，当监听到事件时，则代表获取锁成功<br>因为是临时节点，保证了出现某一台客户端占据锁但是断开连接仍然会删除其创建的临时节点<br>通过这个设计避免了”惊群效应“，某一个锁的释放只会触发刚好晚于他创建临时有序节点的的下一个等待锁的客户端的事件，由其获得锁</p>
<h2 id="demo源码"><a href="#demo源码" class="headerlink" title="demo源码"></a>demo源码</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 基于zk实现分布式锁</span><br><span class="line"> */</span><br><span class="line">public class DistributedLock implements Watcher &#123;</span><br><span class="line">    String ROOT_LOCK;//作为锁的命名空间标识</span><br><span class="line">    String WAIT_LOCK;//正在等待的锁的路径</span><br><span class="line">    String CURRENT_LOCK;//当前请求对应的锁</span><br><span class="line">    ZooKeeper zk;</span><br><span class="line">    CountDownLatch countDownLatch;</span><br><span class="line"></span><br><span class="line">    public DistributedLock(ZooKeeper zk,String ROOT_LOCK)throws Exception&#123;</span><br><span class="line">            this.zk = zk;</span><br><span class="line">            this.ROOT_LOCK = ROOT_LOCK;</span><br><span class="line">            <span class="keyword">if</span>(zk.exists(ROOT_LOCK,<span class="literal">false</span>) == null)&#123;</span><br><span class="line">                throw new Exception(<span class="string">"RootLock node not exists!"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public boolean <span class="function"><span class="title">tryLock</span></span>() &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            CURRENT_LOCK = zk.create(ROOT_LOCK+<span class="string">"/"</span>,<span class="string">"0"</span>.getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);</span><br><span class="line">            List&lt;String&gt; children = zk.getChildren(ROOT_LOCK,<span class="literal">false</span>);</span><br><span class="line">            SortedSet&lt;String&gt; sortChildren = new TreeSet&lt;String&gt;();</span><br><span class="line">            sortChildren.addAll(children);</span><br><span class="line">            //获得排序小于CURRENT_LOCK的childNode的path</span><br><span class="line">            SortedSet&lt;String&gt; lessThanMe = sortChildren.headSet(CURRENT_LOCK);</span><br><span class="line">            <span class="keyword">if</span>(lessThanMe.isEmpty())</span><br><span class="line">                <span class="built_in">return</span> <span class="literal">true</span>;</span><br><span class="line">            <span class="keyword">else</span>&#123;</span><br><span class="line">				//存在小于自己的节点，获取失败</span><br><span class="line">                WAIT_LOCK = lessThanMe.last();</span><br><span class="line">                <span class="built_in">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void <span class="function"><span class="title">lock</span></span>() &#123;</span><br><span class="line">        <span class="keyword">while</span>(!tryLock())&#123;</span><br><span class="line">			//出现异常则继续tryLock</span><br><span class="line">            try &#123;</span><br><span class="line">                <span class="keyword">if</span>(zk.exists(WAIT_LOCK,this)!=null)&#123;</span><br><span class="line">                    countDownLatch = new CountDownLatch(1);</span><br><span class="line">                    countDownLatch.await();</span><br><span class="line">                    //获得锁，结束</span><br><span class="line">                    <span class="built_in">return</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; catch (Exception e)&#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void <span class="function"><span class="title">unlock</span></span>() &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            zk.delete(CURRENT_LOCK,-1);</span><br><span class="line">        &#125; catch (Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void process(WatchedEvent event) &#123;</span><br><span class="line">        <span class="keyword">if</span>(event.getType() == Event.EventType.NodeDeleted)</span><br><span class="line">            countDownLatch.countDown();</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第三方工具也有提供基于zookeeper实现的更多分布式锁的设计，如curator的recipes工程</p>
<h3 id="更多精彩内容"><a href="#更多精彩内容" class="headerlink" title="更多精彩内容"></a>更多精彩内容</h3><h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
  
    <a href="/blog/2019/07/31/zookeeper源码分析-事件注册及通信原理/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">zookeeper源码分析-事件注册及通信原理</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="基于zookeeper实现分布式锁" data-title="基于zookeeper实现分布式锁" data-url="http://eetal.gitee.io/blog/blog/2019/08/01/基于zookeeper实现分布式锁/"  data-images="/blog/images/head.jpg" data-content="基于zookeeper实现分布式锁">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>